<!--柱状图-->
<template>
  <div id="ycbar" :class="className" :style="{height:height,width:width}">{{ycBarQueryResult}}</div>
</template>


<script>
  import echarts from 'echarts'
  require('echarts/theme/macarons')   // echarts theme
  import resize from './../mixins/resize'
  import { listYcBar } from "@/api/dashboard/ycbar";
  import {listYcBarByYear} from "@/api/dashboard/ycbar";

  const animationDuration = 3000
  var seriesArr = [];
  var datalegend = [];
  var ycbarOption= {};
  var sortArray = []


  export default {
    name: 'ycbar',
    mixins: [resize],
    props: {
      ycBarQueryResult: {
        type: Object,
      },
      className: {
        type: String,
        default: 'chart'
      },
      width: {
        type: String,
        default: '100%'
      },
      height: {
        type: String,
        default: '450px'
      }
    },
    data() {
      return {
        dataResult:{
          indeId:null,
          orgId: null,
          dataYear:null,
          dataDimension:null,
        },
        data: {},
        MapList:[],
        rows:[],
        orgId:[],
        dataDimension:[],
        indeName:[],
        dataValue:[],
        dataYear:[],
        orgName: [],
        chart: null,
        indeFlag:[],
        legendIndeDimension:[],
        xAxisData:[],
        seriesArrNew:[],

      }
    },
    mounted() {
      this.$nextTick(() => {
        this.initChart()
      })
    },
    beforeDestroy() {
      if (!this.chart) {
        return
      }
      this.chart.dispose()
      this.chart = null
    },
    created() {

    },
    watch: {
      ycBarQueryResult: {
        handler(newValue) {
          console.log("watch: 监听到的newValue数据如下"+newValue)
          console.log(newValue)
          this.emptyChart();
          this.getBarList(newValue);
          // listYcBar(newValue);
        },
        deep: true
      }
    },
    methods: {
      async getBarList(newValue) {
        this.loading = true;
        console.log("ycbar中ycBarQueryResult的数据:" );
        console.log(this.ycBarQueryResult)
        this.dataResult.indeId = newValue.indeId;
        this.dataResult.dataYear = newValue.dataYear;

        for(let i = 0; i < newValue.orgId.length; i++){
          //101
          this.dataResult.orgId = newValue.orgId[i];
          var sum = 0 //初始化累加器
          var avg = 0
          var orgNameForSort = []
          for (let j = 0; j < newValue.dataDimension.length; j++){
            //1-3月
            this.dataResult.dataDimension = newValue.dataDimension[j];
            console.log("this.dataResult---------------", this.dataResult)

            await listYcBar(this.dataResult).then(response => {
              this.MapList = response.rows;
              console.log("油厂柱状图数据：" + this.MapList);// 确认数据有获取到
              console.log(this.MapList)
              if(this.MapList.length == 0){
                this.$alert('暂无数据', '提示', {
                  confirmButtonText: '确定',
                });
              }
              let MapList = this.MapList;
              if (MapList) {
                let obj = eval(MapList);
                orgNameForSort.push(MapList[0]['ycOrg'].orgName)  //获取一次组织名称
                for (let k = 0; k < obj.length; k++) {
                  sum = sum + MapList[k].dataValue;
                }
                if(j == 0) {
                  this.orgName.push(MapList[j]['ycOrg'].orgName);
                  this.indeFlag.push(MapList[j]['ycInde'].indeFlag);
                  this.indeName.push(MapList[j]['ycInde'].indeName);
                }
              }
            })
          }
          avg = sum / 3        //计算平均值
          sortArray.push({
            orgName: orgNameForSort[0],
            dataValue: this.keepTwoDecimalFull(avg)   //实现累加过程,保留两位小数
          })

        }

          //排序（由大到小）
          sortArray.sort((a, b) =>{
            return b.dataValue - a.dataValue
          })
          console.log("sortArray----------------------after sort", sortArray)
          console.log("--------------------this.orgName")
          console.log(this.orgName)
          console.log("--------------------this.dataDimension")
          console.log(this.dataDimension)
          console.log("--------------------this.indeFlag")
          console.log(this.indeFlag)
          console.log("--------------------this.dataValue")
          console.log(this.dataValue)
        console.log("--------------------this.indeName")
        console.log(this.indeName)
          let seriesDataValue = [];

          for(let i = 0; i < sortArray.length; i++){
            seriesDataValue.push(sortArray[i].dataValue)
            this.xAxisData.push(sortArray[i].orgName)
          }
          // Object.assign(seriesDataValue, this.dataValue)
          seriesDataValue.unshift(null)

          console.log("--------------------seriesDataValue")
          console.log(seriesDataValue)

          seriesArr.push(
            {
              name: this.indeName[0],  //dataDimension[1, 1, 1]
              data: seriesDataValue,
              type: 'bar',
              label:{
                show: true,
                position:'inside',
              },
            })


        Object.assign(this.legendIndeDimension, [this.indeName[0]])

        Object.assign(this.seriesArrNew, seriesArr)

        this.legendIndeDimension.unshift("标杆值")
        this.xAxisData.unshift("标杆值")
        this.seriesArrNew.unshift({
          name: '标杆值',
          type: 'bar',
          color:'#900C3F',
          data: [this.indeFlag[0]],
          // 辅助线相关配置markLine
          markLine: {
            silent: true, //基线显示 隐藏
            symbol:'none',// 不显示箭头和圆点
            label:{
              position: "end",
              color:'#900C3F'
            },
            lineStyle: {
              normal: {
                color: '#900C3F', // 这儿设置安全基线颜色
              },
            },
            data: [
              {
                silent: false,
                name: "标杆值",
                yAxis: this.indeFlag[0],
                label: {
                  formatter: "标杆值"+this.indeFlag[0],
                },
              },
            ]
          },
        })
        console.log("this.legendIndeDimension---------------", this.legendIndeDimension)
        console.log("this.xAxisData---------------", this.xAxisData)
        console.log("this.seriesArrNew---------------", this.seriesArrNew)

        // console.log(seriesArr)
        ycbarOption = {
          legend: {
            data: this.legendIndeDimension,
            orient: 'horizontal',
          },
          xAxis: {
            type: 'category',
            data: this.xAxisData,
            axisLabel: {
              //x轴文字的配置
              show: true,
              interval: 0,//使x轴文字显示全
              rotate: 45
            }
          },
          series: this.seriesArrNew,
        }
        //动态插入数据时，数据在这里设置更新
        this.chart.setOption(ycbarOption);
      },

      initChart() {
        this.chart = echarts.init(this.$el, 'macarons')
        this.chart.setOption(
          {
            tooltip: {
              trigger: 'axis',
              axisPointer: { // 坐标轴指示器，坐标轴触发有效
                type: 'shadow' // 默认为直线，可选为：'line' | 'shadow'
              },
            },
            toolbox: {
              feature: {
                dataZoom: [
                  {
                    type:'inside',
                    orient: 'vertical',
                  },
                  {
                    type: 'inside'
                  }
                ],
                restore: { show: true },
                saveAsImage: { show: true }
              }
            },
            grid: {
              top: 80,
              left: '2%',
              right: '7%',
              bottom: '3%',
              containLabel: true
            },
            xAxis: [{
              type: 'category',
              data: this.orgName,
              axisTick: {
                alignWithLabel: true
              }
            }],
            yAxis: [{
              type: 'value',
              axisTick: {
                show: true
              }
            }],
            label:{
              show: true,
              position:'inside',
            },


          }
        )

      },
      emptyChart(){
        datalegend = [];
        seriesArr = [];
        sortArray = []
        this.orgId=[];
        this.indeFlag=[];
        this.indeName=[];
        this.orgName=[];
        this.dataDimension=[];
        this.dataValue=[];
        this.legendIndeDimension=[],
          this.xAxisData=[],
          this.seriesArrNew=[],
          // this.chart = echarts.init(this.$el, 'macarons')
          this.chart.clear();
        this.chart.setOption(
          {
            legend: {
              data: datalegend,
              orient: 'horizontal',
            },
            toolbox: {
              feature: {
                dataZoom: [
                  {
                    type:'inside',
                    orient: 'vertical',
                  },
                  {
                    type: 'inside'
                  }
                ],
                restore: { show: true },
                saveAsImage: { show: true }
              }
            },
            xAxis: {
              type: 'category',
              data: this.orgName
            },
            series: seriesArr,
            tooltip: {
              trigger: 'axis',
              axisPointer: { // 坐标轴指示器，坐标轴触发有效
                type: 'shadow' // 默认为直线，可选为：'line' | 'shadow'
              },
            },
            grid: {
              top: 80,
              left: '2%',
              right: '7%',
              bottom: '3%',
              containLabel: true
            },
            yAxis: [{
              type: 'value',
              axisTick: {
                show: true
              }
            }],
            label:{
              show: true,
              position:'inside',
            },
          },true)
      },
              //5.四舍五入保留2位小数（不够位数，则用0替补）
         keepTwoDecimalFull(num) {
            var result = parseFloat(num);
            if (isNaN(result)) {
              alert('传递参数错误，请检查！');
              return false;
            }
            result = Math.round(num * 100) / 100;
            var s_x = result.toString(); //将数字转换为字符串

            var pos_decimal = s_x.indexOf('.'); //小数点的索引值


            // 当整数时，pos_decimal=-1 自动补0
            if (pos_decimal < 0) {
              pos_decimal = s_x.length;
              s_x += '.';
            }

            // 当数字的长度< 小数点索引+2时，补0
            while (s_x.length <= pos_decimal + 2) {
              s_x += '0';
            }
            return s_x;
          }
    },
  }
</script>
